#!/bin/sh

if grep "http://www.apache.org/licenses/LICENSE-2.0" "$1" > /dev/null
then
  COPYLINE=`grep -E '^\/\/ Copyright ([12][0-9][0-9][0-9]-)?([1-2][0-9][0-9][0-9])' "$1" | head -n 1`
  
  [ -z "$COPYLINE" ] && exit 0
  
  EDITYEAR=`svn info "$1" | grep "Last Changed Date:" | sed -E -e 's|.*([12][0-9][0-9][0-9]).*|\1|'`
  FIRSTYEAR=`echo "$COPYLINE"| sed -E -e 's|.*[^-]([12][0-9][0-9][0-9]).*|\1|'`
  LASTYEAR=`echo "$COPYLINE"| sed -E -e 's|.*([12][0-9][0-9][0-9]-)?([12][0-9][0-9][0-9]).*|\2|'`
  
  [ -z "$LASTYEAR" ] && exit 1
  
  [ "$LASTYEAR" = "$EDITYEAR" ] && exit 0
    
   sed -E -e "s|// Copyright ([12][0-9][0-9][0-9]-)?[12][0-9][0-9][0-9]|// Copyright $FIRSTYEAR-$EDITYEAR|" "$1" > "$1.hdr" \
   	&& mv "$1.hdr" "$1"
   	
   echo "Updated $1 -> $FIRSTYEAR-$LASTYEAR => $FIRSTYEAR-$EDITYEAR"
else
  grep "<auto-generated>" "$1" > /dev/null && exit 0
  echo "Processing $1"
  YEAR=`svn log -r 0:HEAD "$1" --limit 1 | egrep "^r[0-9]" | sed -E -e 's/.*([0-9]{4})-[0-9]+-[0-9]+.*/\1/'`
  NOWYEAR=`date +%Y`

  svn ps svn:eol-style "native" "$1"
  svn ps svn:keywords "Id" "$1"
  mv "$1" "$1.tmp"
  cat header.txt | \
     sed -e "s/YYYY/$YEAR/" | \
     sed -e "s/ZZZZ/$NOWYEAR/" | \
     sed -e "s/$YEAR-$YEAR/$YEAR/" > "$1.hdr"
   
  dos2unix "$1.tmp"
  utf-combine "$1" "$1.hdr" "$1.tmp" || cat "$1.hdr" "$1.tmp" > "$1"
  rm "$1.tmp" "$1.hdr"
fi
